/* file: zm_loade.c */

#include "zm.h"
#include "zm_loade.h"

static OP_CODE find(char *s)
{
	int i;
	for(i = 0; i < 17; i++)
		if(strcmp(s, find_table[i].str) == 0)
			return find_table[i].mycode;
	return -1;
}

static int find_data(char *s)
{
	if(!strcmp(s, "ax"))
		return 0;
	else if(!strcmp(s, "dx"))
		return 1;
	else 
		return -1;
}


int load_code(void)
{
	int colum, addr, addr1, i;
	OP_CODE op;
	int mydata;
	int num;
	char word_str[10];
	for(i = 0; i < 1024; i++)
	{
		code_mem[i].op_code = code_mem[i].data1.flag = code_mem[i].data1.data = -1;
		code_mem[i].data2.flag = code_mem[i].data2.data = -1;
	}
	while(!feof(asm_point))
	{
		fgets(buffer, 99, asm_point);
		colum = addr = addr1 = i = num= 0;
		op = -1;
		while(buffer[colum] == ' ')                       /* skip blank */
			colum ++;
		/* The code's address */
		while(isdigit(buffer[colum]))
			addr = addr * 10 + buffer[colum++] - '0';
		while(!isalpha(buffer[colum]))                    /* skip blank and : etc...*/
			colum++;
		/* The oprand code  */
		while(isalpha(buffer[colum]))
			word_str[i++] = buffer[colum++];
		word_str[i] = '\0';
		op = find(word_str);
		code_mem[addr].op_code = op;

		while(buffer[colum] == ' ')                      /* skip blank */
			colum ++;
		i = 0;
		/* The first oprand data */
		if(isdigit(buffer[colum]))
		{
			while(isdigit(buffer[colum]))
				addr1 = addr1 *10 + buffer[colum++] - '0';
			code_mem[addr].data1.flag = MEM_FLAG;
			code_mem[addr].data1.data = addr1;
		}
		else
		{
			while(isalpha(buffer[colum]))
				word_str[i++] = buffer[colum++];
			word_str[i] = '\0';
			mydata = find_data(word_str);   
			code_mem[addr].data1.flag = REG_FLAG;
			code_mem[addr].data1.data = mydata;     
		}

		while(buffer[colum] == ' ')
			colum ++;

		if(buffer[colum] == ',')
		{
			colum ++;
			while(buffer[colum] == ' ')
				colum ++;
			if(buffer[colum] == '#')
			{
				colum ++;
				while(isdigit(buffer[colum]))
					num = num *10 + buffer[colum++] - '0';
				code_mem[addr].data2.flag = DATA_FLAG;
				code_mem[addr].data2.data = num;
			}
			else if(isdigit(buffer[colum]))
			{
				while(isdigit(buffer[colum]))
					num = num * 10 + buffer[colum++] - '0';
				code_mem[addr].data2.flag = MEM_FLAG;
				code_mem[addr].data2.data = num;
			}
			else 
			{
				i = 0;
				while(isalpha(buffer[colum]))
					word_str[i++] = buffer[colum++];
				word_str[i] = '\0';
				mydata = find_data(word_str);
				code_mem[addr].data2.flag = REG_FLAG;
				code_mem[addr].data2.data = mydata;
			}
		}

	}
	return 1;
}















